package xyz.gzdxc.common.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import xyz.gzdxc.common.mysql.entity.SessionEntity;
import xyz.gzdxc.common.mysql.repository.SessionRepository;
import xyz.gzdxc.common.service.SessionService;
import xyz.gzdxc.common.util.DateUtil;
import xyz.gzdxc.common.vo.response.CheckSessionResp;

import java.util.Date;

@Service
public class SessionServiceImpl implements SessionService {

    @Autowired
    SessionRepository sessionRepository;

    @Override
    public CheckSessionResp checkSession(String loginSession) {
        CheckSessionResp checkSessionResp = new CheckSessionResp();
        if(null == loginSession || "".equals(loginSession)){
            checkSessionResp.setSessionTimeOutFlag(true);
            checkSessionResp.setTimeOutFlag(true);
            return checkSessionResp;
        }
        SessionEntity session = sessionRepository.findByLoginSession(loginSession);
        if(session == null){
            checkSessionResp.setSessionTimeOutFlag(true);
            checkSessionResp.setTimeOutFlag(true);
        }else{
            //check whether the session timeout or not
            int i = session.getSessionTimeOut().compareTo(new Date());
            if(i <= 0){
                checkSessionResp.setSessionTimeOutFlag(true);
                sessionRepository.deleteById(session.getId());
            }
            //check whether login timeout or not
            long noActionMin = DateUtil.getTimeDiffInMin(session.getUpdateTime());
            if(noActionMin >= session.getTimeOut()){
                checkSessionResp.setTimeOutFlag(true);
                sessionRepository.deleteById(session.getId());
            } else {
                sessionRepository.modifyUpdateTimeById(new Date(), session.getId());
            }
        }
        return checkSessionResp;
    }

}
